package com.cyyl.updater.download

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.cyyl.updater.AppUpdater
import java.io.File

/**
 * @author : Android-张康
 * created on: 2021/8/11 15:07
 * description:
 */
object InstallApkHelper {

    private const val TAG = "InstallApkHelper"

    /**
     * 检查是否可以更新
     *
     * @param context 上下文
     * @param uri 本地路径
     * @return true可以升级 false 不能升级
     */
    fun checkCanUpdate(context: Context, uri: Uri): Boolean {
        //获取apk的信息
        val apkInfo = getApkInfo(context, uri) ?: return false
        //获取当前app的包名
        val packageName = context.packageName
        val packageInfo = context.packageManager.getPackageInfo(packageName, 0)
        if (apkInfo.packageName != packageName) {
            return false
        }
        val apkInfoVerCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            apkInfo.longVersionCode
        } else {
            apkInfo.versionCode.toLong()
        }
        val packageInfoVerCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            packageInfo.longVersionCode
        } else {
            packageInfo.versionCode.toLong()
        }
        if (packageInfoVerCode <= apkInfoVerCode) {
            return true
        }
        return false
    }

    fun installApk(context: Context, downloadFileUri: Uri) {
        val apkFilePath: String = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            val cursor: Cursor =
                context.contentResolver.query(downloadFileUri, null, null, null, null)
                    ?: return
            val filePath = if (cursor.moveToNext()) {
                cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA))
            } else {
                return
            }
            cursor.close()
            filePath
        } else {
            val path = downloadFileUri.path ?: return
            path
        }
        installApk(context, File(apkFilePath))
    }

    /**
     * 安装Apk文件
     */
    private fun installApk(context: Context, file: File) {
        if (!file.exists()) {
            return
        }
        val fileUri = Uri.fromFile(file)
        val fileUriPath = fileUri.path ?: return
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val apkFile = File(fileUriPath)
            //参数1 上下文,
            //参数2 Provider主机地址 和配置文件中保持一致
            //参数3 共享的文件
            val apkUri =
                FileProvider.getUriForFile(context, AppUpdater.authority, apkFile)
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive")
        }
        context.startActivity(intent)
    }


    private fun getApkInfo(context: Context, uri: Uri): PackageInfo? {
        val apkFilePath: String = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            val cursor: Cursor =
                context.contentResolver.query(uri, null, null, null, null) ?: return null
            val filePath = if (cursor.moveToNext()) {
                cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA))
            } else {
                return null
            }
            cursor.close()
            filePath
        } else {
            val path = uri.path ?: return null
            path
        }
        return context.packageManager.getPackageArchiveInfo(apkFilePath, 0)
    }


}